package com.qianfeng.smartdevice.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartdevice.pojo.Humiture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

import java.util.Date;
import java.util.Map;

@Component
@EnableWebSocket
public class HumitureWebsocket extends MyBaseWebsocketHandler {
    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //此处我们保留了 super 原因是因为父类中的当前方法是有实现的并且这个实现是我们需要的,所以我们直接调用,我们只需要扩展我们自己的功能即可
        super.handleTextMessage(session, message);

        try {
            //处理设备发送过来的数据
            //设备发送过来的是一个 json
            String jsonString = message.getPayload();
            Map map = objectMapper.readValue(jsonString, Map.class);
            //"{\"humidity\":"+String(humidity)+",\"temperature\":"+String(temp_f)+"}";
            Double humidity = (Double) map.get("humidity");//湿度
            Double temperature = (Double) map.get("temperature");//温度,注意此处的格式是华氏温度
            //5×(F-32)/9
            System.err.println("收到的湿度是 :====>" + humidity + "----->温度是:-==>" + temperature);
            String uuid = (String) session.getAttributes().get("uuid");//设备的编号
            //TODO 发送事件,把上面的数据带出去,温湿度 service
            Humiture humiture = new Humiture();
            humiture.setHumidity(humidity);
            humiture.setTemperature(temperature);
            humiture.setDeviceUuid(uuid);
            humiture.setUploaddate(new Date());
            context.publishEvent(humiture);//发布事件
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
